<template>
  <div class="sidebar-content">
    <h3>基础形状</h3>
    <div class="shape-tools">
      <div class="tool-item" @click="console.log('MaterialPanel: Emitting add-shape rect'); emit('add-shape', 'rect')">
        <div class="tool-icon">■</div>
        <div class="tool-name">矩形</div>
      </div>
      <div class="tool-item" @click="console.log('MaterialPanel: Emitting add-shape circle'); emit('add-shape', 'circle')">
        <div class="tool-icon">●</div>
        <div class="tool-name">圆形</div>
      </div>
      <div class="tool-item" @click="console.log('MaterialPanel: Emitting add-shape triangle'); emit('add-shape', 'triangle')">
        <div class="tool-icon">▲</div>
        <div class="tool-name">三角形</div>
      </div>
      <div class="tool-item" @click="console.log('MaterialPanel: Emitting add-shape polygon'); emit('add-shape', 'polygon')">
        <div class="tool-icon">⬡</div>
        <div class="tool-name">多边形</div>
      </div>
      <div class="tool-item" @click="console.log('MaterialPanel: Emitting add-shape line'); emit('add-shape', 'line')">
        <div class="tool-icon">╱</div>
        <div class="tool-name">直线</div>
      </div>
    </div>
    
    <h3>设计素材</h3>
    <div class="material-grid">
      <div 
        v-for="material in materials" 
        :key="material.name" 
        class="material-item"
        @click="console.log('MaterialPanel: Emitting add-material', material); emit('add-material', material.name)"
      >
        <img :src="material.url" :alt="material.name">
        <div class="material-name">{{ material.name }}</div>
      </div>
    </div>
    
    <h3>上传图片</h3>
    <div class="upload-section">
      <button class="upload-button">
        选择图片
        <input type="file" accept="image/*" @change="handleImageUpload">
      </button>
      <div class="upload-hint">支持JPG、PNG、SVG格式</div>
    </div>
    
    <h3>背景设置</h3>
    <div class="background-settings">
      <div class="background-options">
        <label>
          <input 
            type="radio" 
            :value="'color'" 
            v-model="localBackgroundType"
            @change="updateBackgroundType"
          >
          纯色背景
        </label>
        <label>
          <input 
            type="radio" 
            :value="'gradient'" 
            v-model="localBackgroundType"
            @change="updateBackgroundType"
          >
          渐变背景
        </label>
        <label>
          <input 
            type="radio" 
            :value="'image'" 
            v-model="localBackgroundType"
            @change="updateBackgroundType"
          >
          图片背景
        </label>
      </div>
      
      <div v-if="localBackgroundType === 'color'" class="background-color-picker">
        <label>背景颜色:</label>
        <input 
          type="color" 
          v-model="localBackgroundColor"
          @input="logAndEmitBackgroundColor"
        >
      </div>
      
      <div v-if="localBackgroundType === 'gradient'" class="background-gradient">
        <div class="gradient-preview" :style="gradientStyle"></div>
        <div class="gradient-inputs">
          <div class="color-input">
            <label>起始颜色:</label>
            <input type="color" v-model="gradientStartColor">
          </div>
          <div class="color-input">
            <label>结束颜色:</label>
            <input type="color" v-model="gradientEndColor">
          </div>
          <div class="gradient-type">
            <label>方向:</label>
            <select v-model="gradientDirection">
              <option value="linear-to-right">从左到右</option>
              <option value="linear-to-bottom">从上到下</option>
              <option value="radial">径向渐变</option>
            </select>
          </div>
          <button class="apply-gradient" @click="applyGradient">应用渐变</button>
        </div>
      </div>
      
      <div v-if="localBackgroundType === 'image'" class="background-image">
        <button class="upload-button">
          选择背景图
          <input type="file" accept="image/*" @change="handleBackgroundImageUpload">
        </button>
        <div class="background-options">
          <label>
            <input type="checkbox" v-model="backgroundImageOptions.repeat">
            平铺背景
          </label>
          <label>
            <input type="checkbox" v-model="backgroundImageOptions.stretch">
            拉伸适应
          </label>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, defineProps, defineEmits, toRefs, watch } from 'vue';

// --- Props --- 
const props = defineProps<{
  materials?: Array<{ name: string; url: string }>; // 添加类型
  backgroundType?: string;
  backgroundColor?: string;
}>();

// 使用 toRefs 保持响应性，特别是对于需要在模板中直接使用的 props
// 或者在 data 中创建本地响应式引用

// --- Emits --- 
const emit = defineEmits<{
  (e: 'add-shape', type: string): void;
  (e: 'add-material', id: string): void;
  (e: 'upload-image', dataUrl: string): void;
  (e: 'apply-background', color: string): void;
  (e: 'backgroundTypeChange', type: string): void;
  (e: 'backgroundColorChange', color: string): void;
  (e: 'backgroundGradientChange', payload: { startColor: string; endColor: string; direction: string }): void;
  (e: 'backgroundImageChange', payload: { file: File; options: { repeat: boolean; stretch: boolean } }): void;
}>();

// --- Reactive State (替代 data) ---
const localBackgroundType = ref(props.backgroundType || 'color');
const localBackgroundColor = ref(props.backgroundColor || '#ffffff');
const gradientStartColor = ref('#1890ff');
const gradientEndColor = ref('#f759ab');
const gradientDirection = ref('linear-to-right');
const backgroundImageOptions = reactive({
  repeat: false,
  stretch: true
});

// --- Computed Properties ---
const gradientStyle = computed(() => {
  let gradient;
  if (gradientDirection.value === 'linear-to-right') {
    gradient = `linear-gradient(to right, ${gradientStartColor.value}, ${gradientEndColor.value})`;
  } else if (gradientDirection.value === 'linear-to-bottom') {
    gradient = `linear-gradient(to bottom, ${gradientStartColor.value}, ${gradientEndColor.value})`;
  } else {
    gradient = `radial-gradient(circle, ${gradientStartColor.value}, ${gradientEndColor.value})`;
  }
  return { background: gradient };
});

// --- Methods ---
function updateBackgroundType() {
  emit('backgroundTypeChange', localBackgroundType.value);
}

function applyGradient() {
  emit('backgroundGradientChange', {
    startColor: gradientStartColor.value,
    endColor: gradientEndColor.value,
    direction: gradientDirection.value
  });
}

function handleImageUpload(event: Event) {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    const imgDataUrl = e.target?.result;
    if (typeof imgDataUrl === 'string') { // 检查类型
      console.log('MaterialPanel: Emitting upload-image');
      emit('upload-image', imgDataUrl);
    } else {
      console.error('Failed to read image data as string');
    }
  };
  reader.onerror = (error) => {
      console.error('FileReader error:', error);
  };
  reader.readAsDataURL(file);
  target.value = ''; // 清空以便重新上传
}

function handleBackgroundImageUpload(event: Event) {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  emit('backgroundImageChange', {
    file,
    options: { ...backgroundImageOptions } // 传递副本
  });
  target.value = ''; // 清空
}

function logAndEmitBackgroundColor(event: Event) {
  const color = (event.target as HTMLInputElement).value;
  console.log('MaterialPanel: Emitting apply-background with color:', color); // 添加日志
  emit('apply-background', color);
}

// --- Watchers (同步 props 到本地状态) ---
watch(() => props.backgroundType, (newVal) => {
  localBackgroundType.value = newVal || 'color';
});

watch(() => props.backgroundColor, (newVal) => {
  localBackgroundColor.value = newVal || '#ffffff';
});

// --- Cleanup script tag --- (移除 Options API 的 script 标签)

</script>

<style scoped>
.sidebar-content {
  padding: 12px;
  overflow-y: auto;
  height: 100%;
  background-color: #f9fafc;
  scrollbar-width: thin;
}

/* 优化滚动条样式 */
.sidebar-content::-webkit-scrollbar {
  width: 6px;
}

.sidebar-content::-webkit-scrollbar-track {
  background: transparent;
}

.sidebar-content::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.15);
  border-radius: 3px;
}

.sidebar-content::-webkit-scrollbar-thumb:hover {
  background-color: rgba(0, 0, 0, 0.25);
}

h3 {
  font-size: 15px;
  margin-bottom: 12px;
  margin-top: 20px;
  color: #262626;
  font-weight: 600;
  position: relative;
  padding-left: 10px;
  letter-spacing: 0.2px;
}

h3:first-child {
  margin-top: 6px;
}

h3::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 3px;
  height: 16px;
  background: linear-gradient(to bottom, #1890ff, #36cfc9);
  border-radius: 2px;
}

/* 简化标题下方的指示条 */
h3::after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  right: 0;
  bottom: -6px;
  height: 1px;
  background: linear-gradient(to right, rgba(24, 144, 255, 0.1), rgba(54, 207, 201, 0));
}

.shape-tools {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 6px;
  margin-bottom: 20px;
}

.tool-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 65px;
  border: 1px solid #eaeaea;
  border-radius: 6px;
  background-color: #fff;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
}

.tool-item:hover {
  transform: translateY(-2px);
  border-color: #1890ff;
  background-color: #f0f9ff;
  box-shadow: 0 3px 8px rgba(24, 144, 255, 0.12);
}

.tool-icon {
  font-size: 24px;
  margin-bottom: 6px;
  transition: transform 0.2s ease, color 0.2s ease;
  color: #595959;
}

.tool-item:hover .tool-icon {
  transform: scale(1.1);
  color: #1890ff;
}

.tool-name {
  font-size: 12px;
  color: #555;
  transition: color 0.2s ease;
}

.tool-item:hover .tool-name {
  color: #1890ff;
}

.material-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
  margin-bottom: 20px;
}

.material-item {
  border: 1px solid #eaeaea;
  border-radius: 6px;
  overflow: hidden;
  cursor: pointer;
  background-color: #fff;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
}

.material-item:hover {
  transform: translateY(-2px);
  border-color: #1890ff;
  box-shadow: 0 3px 8px rgba(24, 144, 255, 0.12);
}

.material-item img {
  width: 100%;
  height: auto;
  display: block;
  transition: all 0.3s;
}

.material-item:hover img {
  filter: brightness(1.05);
}

.material-name {
  padding: 8px;
  font-size: 12px;
  color: #555;
  text-align: center;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
  transition: all 0.2s;
}

.material-item:hover .material-name {
  background-color: #e6f7ff;
  color: #1890ff;
}

.upload-section {
  margin-bottom: 20px;
  background-color: white;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
}

.upload-button {
  width: 100%;
  height: 36px;
  position: relative;
  overflow: hidden;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  background-color: #fafafa;
  cursor: pointer;
  transition: all 0.2s;
  text-align: center;
  line-height: 36px;
  color: #555;
  font-size: 14px;
}

.upload-button:hover {
  border-color: #1890ff;
  color: #1890ff;
  background-color: #f0f9ff;
}

.upload-button input[type="file"] {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  opacity: 0;
  cursor: pointer;
}

.upload-hint {
  margin-top: 8px;
  font-size: 12px;
  color: #888;
  text-align: center;
}

.background-settings {
  margin-bottom: 20px;
  background-color: white;
  padding: 12px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.02);
}

.background-options {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 12px;
}

.background-options label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
  color: #555;
  cursor: pointer;
  transition: color 0.2s;
  padding: 4px 0;
}

.background-options label:hover {
  color: #1890ff;
}

.background-options input[type="radio"] {
  accent-color: #1890ff;
  width: 14px;
  height: 14px;
}

.background-color-picker {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 6px 0;
  margin-top: 4px;
  border-top: 1px solid #f0f0f0;
}

.background-color-picker label {
  font-size: 13px;
  color: #555;
}

.background-color-picker input[type="color"] {
  width: 80px;
  height: 32px;
  border: 1px solid #d9d9d9;
  padding: 2px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.background-color-picker input[type="color"]:hover {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.background-gradient {
  margin-top: 12px;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.gradient-preview {
  width: 100%;
  height: 50px;
  border-radius: 6px;
  margin-bottom: 12px;
  border: 1px solid #eaeaea;
  box-shadow: inset 0 0 3px rgba(0, 0, 0, 0.05);
}

.gradient-inputs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.color-input label, .gradient-type label {
  display: block;
  font-size: 12px;
  color: #555;
  margin-bottom: 4px;
}

.color-input input[type="color"] {
  width: 100%;
  height: 32px;
  border: 1px solid #d9d9d9;
  padding: 2px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.color-input input[type="color"]:hover {
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.gradient-type select {
  width: 100%;
  height: 32px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  padding: 0 8px;
  color: #555;
  transition: all 0.2s;
  cursor: pointer;
}

.gradient-type select:hover {
  border-color: #40a9ff;
}

.gradient-type select:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
  outline: none;
}

.apply-gradient {
  grid-column: span 2;
  height: 34px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
  margin-top: 10px;
  font-size: 13px;
  font-weight: 500;
}

.apply-gradient:hover {
  background-color: #40a9ff;
  box-shadow: 0 3px 8px rgba(24, 144, 255, 0.2);
}

.apply-gradient:active {
  background-color: #096dd9;
}

.background-image {
  margin-top: 12px;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.background-image .upload-button {
  margin-bottom: 12px;
}

.background-image .background-options {
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 8px;
}

.background-image .background-options label {
  padding: 3px 0;
}

.background-image .background-options input[type="checkbox"] {
  accent-color: #1890ff;
  width: 14px;
  height: 14px;
}

/* 响应式调整：在较小的视口高度下压缩UI */
@media (max-height: 768px) {
  h3 {
    margin-top: 16px;
    margin-bottom: 10px;
    font-size: 14px;
  }
  
  .shape-tools {
    margin-bottom: 16px;
  }
  
  .tool-item {
    height: 60px;
  }
  
  .material-grid, .upload-section, .background-settings {
    margin-bottom: 16px;
  }
  
  .gradient-preview {
    height: 40px;
  }
}
</style> 